<template>
  <s-layout
    title="我的"
    type="user"
    navbar="inner"
    tabbar="/pages/message/user"
    color="#000000"
    :onShareAppMessage="shareMessage"
    :leftIcon="''"
    :bgStyle="template.style?.background"
    :navbarStyle="template.style?.navbar"
    :showFloatButton="true"
    :showLeftHome="false"
    showAddIcon
    mainBackground="#F5F5F5"
  >
    <s-block v-for="(item, index) in template.data" :key="index" :styles="item.style">
      <s-block-item :type="item.type" :data="item.data" :styles="item.style">
        <template #ncVip v-if="index == 0">

        </template>
      </s-block-item>
    </s-block>
    <view class="mainPopup flex flex-column justify-center align-center" :style="mainStyle()" @click.stop="goPath">
      <!--      <view class="top flex flex-row align-center">-->
      <!--        <image src="/static/nc_user_icon.png" :style="setImageStyle(26,19)"></image>-->
      <!--        <view style="margin-left: 5rpx;">暖晨Ai-有温度的生成式人工智能</view>-->
      <!--      </view>-->
      <!--      <view class="bottom">-->
      <!--        技术支持: 晨曦软件-->
      <!--      </view>-->
      <view class="top flex flex-row align-center">
        <!--        <image src="/static/nc_user_icon.png" :style="setImageStyle(26,19)"></image>-->
        <view style="color: rgba(136,134,126,0.6)">再小的家庭&nbsp;&nbsp;也可以有传承</view>
      </view>
    </view>
    <s-login-popup ref="loginPopup" @confirm="loginConfirm"></s-login-popup>

    <s-popup-vip :show="vipDisposition.isShow" @closePopup="closePopup">
      <template #default>
        <view class="memberPopup position-relative"
              v-if="!!vipDisposition.goodDetails && vipDisposition.goodDetails != {}">
          <image class="w-100 h-100" :src="`${nc_image_path}/nc_vip_banner.png`"></image>
          <view class="exchange flex align-center justify-between">
            <view class="flex align-end" v-if="!!vipDisposition.goodDetails.price">
              <text>￥</text>
              <text class="fs_60" style="line-height: 60rpx">{{ vipDisposition.goodDetails.price[0] }}</text>
            </view>
            <view @click.stop="exchangeImmediately" v-if="mp_code != appVersion">
              兑换
            </view>
          </view>
          <view class="chatDetail fs_26 fw_500" style="color: #FDD07F"
                @click.stop="sheep.$router.go('/pages/public/richtext',{id:4,title:'会员权益'})"
          >
            查看详情
          </view>
          <view class="button_vip flex flex-row align-center justify-center" @click.stop="purchaseMembership">
            立即开通
          </view>
        </view>
      </template>
    </s-popup-vip>
  </s-layout>
</template>

<script setup>
  import { computed, onMounted, ref, reactive } from 'vue';
  import { onShow, onReady, onPullDownRefresh } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import SLayout from '@/sheep/components/s-layout/s-layout.vue';
  import { showAuthModal } from '@/sheep/hooks/useModal';
  import { h5_url } from '@/sheep/config';
  import SPopupVip from '@/sheep/components/s-popup-vip/s-popup-vip.vue';


  // 隐藏原生tabBar
  uni.hideTabBar({
    fail: () => {
    },
  });
  // #ifndef APP-PLUS
  let shareMessage = ref(true);
  // #endif
  // #ifdef APP-PLUS
  let shareMessage = ref({
    title: '拾亲',
    desc: '再小的家庭-也要有传承',
    link: 'https://a.shiqin.cc',
    image: 'https://a.shiqin.cc/static/fenxiang_icon.png',
    poster: {
      type: 'user',
    },
  });
  // #endif
  const template = computed(() => sheep.$store('app').template.user);
  const mainStyle = () => {
    return {
      'margin-top': '60rpx',
      'margin-bottom': '10px',
    };
  };
  const isLogin = computed(() => sheep.$store('user').isLogin);
  // #ifdef H5
  const userInfo = computed(() => JSON.parse(uni.getStorageSync('user-store')).userInfo);
  // #endif
  // #ifndef H5
  const userInfo = computed(() => sheep.$store('user').userInfo);
  // #endif
  const loginPopup = ref();
  const setImageStyle = (width, height) => {
    return {
      width: `${width}rpx`,
      height: `${height}rpx`,
    };
  };
  const mp_code = computed(() => sheep.$store('AI').mp_code);
  const version = computed(() => sheep.$store('AI').version);
  const appVersion = computed(() => sheep.$store('app').info.worship_version);
  const vipDisposition = reactive({
    isShow: false,
    goodDetails: {},
  });
  const nc_image_path = computed(() => sheep.$store('AI').nc_image_path);

  onShow(() => {
    sheep.$store('user').updateUserData();
    if (!!isLogin.value) {
      if (!userInfo.value.surname || !userInfo.value.daimyo) {
        uni.redirectTo({
          url: '/pages/userData/sex',
        });
        return;
      }
      sheep.$store('AI').setUserFamily();
    }
  });

  onReady(async () => {
    const { data } = await sheep.$api.goods.ids({ ids: '10' });
    vipDisposition.goodDetails = data[0];
    // #ifdef APP-PLUS
    shareMessage = {
      title: '拾亲',
      desc: '再小的家庭-也要有传承',
      link: `${h5_url}/#/pages/message/genealogy?id=${userInfo.value.uid}`,
      image: `${h5_url}/static/shiqin_transparent_icon.png`,
    };
    // #endif
    uni.$on('iosPay', () => {
      openVip();
    });
  });

  onMounted(() => {
    uni.$on('openLoginPopup', () => {
      loginPopup._value.openPopup();
    });
    if (!isLogin.value) {
      loginPopup._value.openPopup();
    }
  });

  onPullDownRefresh(() => {
    sheep.$store('user').updateUserData();
    setTimeout(function() {
      uni.stopPullDownRefresh();
    }, 800);
  });

  function goPath() {
    return;
    sheep.$router.go('/pages/public/richtext', { id: 3, title: '关于我们' });
  }

  function loginConfirm() {
    loginPopup._value.closePopup();
    showAuthModal();
    sheep.$router.go('/pages/login/wechat_login');
  }

  async function purchaseMembership() {
    let obj = {};
    let arr = [];
    arr.push({
      goods_id: vipDisposition.goodDetails.id,
      goods_num: 1,
      goods_sku_price_id: vipDisposition.goodDetails.id,
    });
    obj.goods_list = arr;
    obj.is_from = 1;
    obj.order_type = 'goods';
    const { code, data } = await sheep.$api.order.create(obj);
    // #ifdef APP-PLUS
    if (sheep.$platform.device.platform.toLocaleLowerCase() == 'ios' && mp_code.value == appVersion.value) {
      plus.payment.getChannels(async function(channels) {
        for (let i in channels) {
          let channel = channels[i];
          // 获取 id 为 'appleiap' 的 channel
          if (channel.id == 'appleiap') {
            console.log(data.order_sn);
            const data1 = await sheep.$api.order.detail(data.order_sn);
            channel.requestOrder(['io.shiqin.app.com_Member_oneYear'], (res) => {
              applePay(res[0], data.order_sn);
            }, (err) => {
              console.log('内购失败=>', err);
            });
          }
        }
      }, function(e) {
        sheep.$helper.toast('获取iap支付通道失败：' + e.message);
      });
      return;
    }
    // #endif
    sheep.$router.go('/pages/pay/index', {
      orderSN: data.order_sn,
      flag: 1,
    });
  }

  function exchangeImmediately() {
    sheep.$router.go('/pages/vip/memberCenter');
  }

  function closePopup() {
    vipDisposition.isShow = false;
  }

  function openVip() {
    vipDisposition.isShow = true;
  }

  // #ifdef APP-PLUS
  function applePay(order, order_id) {
    uni.showLoading({
      title: '充值中请勿离开',
      mask: true,
    });
    uni.requestPayment({
      provider: 'appleiap',
      orderInfo: {
        productid: order.productid,
      },
      success: (async res => {
        console.log(res);
        uni.hideLoading();
        const { code, msg } = await sheep.$api.user.applePay({
          order_id,
          transactionReceipt: res.transactionReceipt,
          transactionIdentifier: res.transactionIdentifier,
        });
        console.log(code, msg);
        if (code == 1) {
          uni.showModal({
            content: '支付成功',
            showCancel: false,
          });
          vipDisposition.isShow = false;
          sheep.$store('user').updateUserData();
        } else {
          uni.showModal({
            content: '支付失败',
            showCancel: false,
          });
        }
      }),
      fail: (e) => {
        uni.hideLoading();
        uni.showModal({
          content: '支付失败',
          showCancel: false,
        });
      },
    });
  }

  // #endif
</script>

<style lang="scss">
  .mainPopup {
    padding: 50rpx 0;

    .top {
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      font-size: 24rpx;
      color: #605442;
    }

    .bottom {
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      font-size: 20rpx;

      color: #484136;
    }
  }


  .memberPopup {
    width: 750rpx;
    height: 789rpx;

    .exchange {
      width: 325rpx;
      position: absolute;
      right: 215rpx;
      top: 154rpx;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 500;
      font-size: 28rpx;
      color: #E94F09;
      padding: 0 0 5rpx 0;
    }
  }

  .button_vip {
    position: absolute;
    left: 50%;
    bottom: 110rpx;
    transform: translate(-50%, 0);
    width: 269rpx;
    height: 82rpx;
    background: url($uni-bg-url + '/nc_vip_button.png') no-repeat;
    background-size: 269rpx 82rpx;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 500;
    font-size: 41rpx;
    color: #FF4206;
  }

  .chatDetail {
    position: absolute;
    left: 50%;
    bottom: 270rpx;
    transform: translate(-50%, 0);
  }
</style>
